//
//  QRNetHelper.m
//  CreateCode
//
//  Created by zhibao on 2024/1/25.
//

#import "QRNetHelper.h"
#import "ResponseModel.h"
#import "ErrorHelpler.h"
#import "TimeHelper.h"
#import "sys/utsname.h"
@implementation QRNetHelper

+ (instancetype)sharedInstance{
    static dispatch_once_t token;
    static id instance = nil;
    dispatch_once(&token, ^{
        instance = [[self alloc] initWithServer:QR_HTTP_SERVE];
    });
    return instance;
}

- (id)initWithServer:(NSString *)server{
    self = [super init];
    if (self){
        NSURL *url = [NSURL URLWithString:server];
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
        manager.requestSerializer.timeoutInterval = 60;
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        [securityPolicy setValidatesDomainName:NO];
        [securityPolicy setAllowInvalidCertificates:YES];
        [manager setSecurityPolicy:securityPolicy];
        self.manager = manager;
    }
    
    return self;
}

//发起请求
- (void)sendPost:(NSString *)URLString
      parameters:(NSDictionary *)parameters
         success:(void (^)(NSURLSessionTask *operation, ResponseModel *responseObject))success
         failure:(void (^)(NSURLSessionTask *operation, NSError *error))failure {
    [QMUITips showLoadingInView:MYAPP.window];
    
    NSDictionary *headers = @{ @"Authorization": @"Bearer ebb356c0-4870-11ee-a787-5bddcaf194da",
                               @"Content-Type": @"application/json",
                               @"Accept": @"application/json" };
    
    NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.erweicaihong.cn/qrcodes/qr2"]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setAllHTTPHeaderFields:headers];
    [request setHTTPBody:postData];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"%@", error);
        } else {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
            NSLog(@"%@", httpResponse);
            NSDictionary *temp1 =  [Helper dictionaryForJsonData:data];
            ResponseModel *contentModel = [self getResponseModel:URLString withObject:temp1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (contentModel) {
                    success(dataTask, contentModel);
                }else{
                    failure(dataTask,nil);
                }
                [QMUITips hideAllTipsInView:MYAPP.window];
            });
            
        }
    }];
    [dataTask resume];
    
    
    
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:parameters];
//    //    if (![dic[@"http_type"] isEqualToString:@"1"]) {
//    //        [dic removeObjectForKey:@"http_type"];
//    //        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    //        [self.manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    //    }else{
//    self.manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json",@"text/javascript",@"application/html",@"application/x-www-form-urlencoded", nil];
//
//    //申明返回的结果是json类型
//    self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
//
//    //申明请求的数据是json类型
//    self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    //    }
//    [self setCommonHeaderParameters];
//    DLog(@"[self addSign:dic]===%@",[self addSign:dic]);
//    [self.manager POST:URLString parameters:[self addSign:parameters]  headers:headers progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//        [QMUITips hideAllTipsInView:MYAPP.window];
//
//        ResponseModel *contentModel = [self getResponseModel:URLString withObject:responseObject];
//        if (contentModel) {
//            success(task, contentModel);
//        }else{
//            failure(task,nil);
//        }
//
//    } failure:^(NSURLSessionTask *task, NSError *error) {
//        [QMUITips hideAllTipsInView:MYAPP.window];
//        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
//        DLog(@"1111111111111111:%ld",    responses.statusCode);
//
//        if (responses.statusCode == 401) {
//
//            DLog(@"登录信息失效，请重新登录");
//            [HttpHelper cancelAllRequest];
//            [[UserInfoManager sharedManager] initEmptyData];
//            [[UserInfoManager sharedManager] Login];
//            return;
//        }
//
//        if ([error.domain isEqualToString:AFURLResponseSerializationErrorDomain]) {
//
//            // server error
//            id response = [NSJSONSerialization JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
//            DLog(@"****%@",response);
//
//            NSString *message = [NSString stringWithFormat:@"%@",response[@"message"]];
//            NSString *status = [NSString stringWithFormat:@"%@",response[@"status"]];
//            DLog(@"*****%@----%@",status,message);
//
//            [ErrorHelpler showError:message];
//
//            // response中包含服务端返回的内容
//        } else if ([error.domain isEqualToString:NSCocoaErrorDomain]) {
//            // server throw exception
//            [ErrorHelpler showError:error.localizedDescription];
//
//        } else if ([error.domain isEqualToString:NSURLErrorDomain]) {
//            // network error
//            [ErrorHelpler showError:error.localizedDescription];
//        }
//        failure(task, error);
//        DLog(@"\n\nRESPONSE-URL:%@\nERROR:%@", URLString, error);
//    }];
}

//发起请求
- (void)sendPut:(NSString *)URLString
     parameters:(NSDictionary *)parameters
        success:(void (^)(NSURLSessionTask *operation, ResponseModel *responseObject))success
        failure:(void (^)(NSURLSessionTask *operation, NSError *error))failure {
    [QMUITips showLoadingInView:MYAPP.window];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:parameters];
    if (![dic[@"http_type"] isEqualToString:@"1"]) {
        [dic removeObjectForKey:@"http_type"];
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [self.manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    }else{
        self.manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json",@"image/jpeg", @"image/png", @"application/octet-stream", @"text/json",@"text/javascript",@"application/html",@"application/x-www-form-urlencoded", nil];
        
        //申明返回的结果是json类型
        self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        //申明请求的数据是json类型
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    [self setCommonHeaderParameters];
    [self.manager PUT:URLString parameters:[self addSign:dic] headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [QMUITips hideAllTipsInView:MYAPP.window];
        ResponseModel *contentModel = [self getResponseModel:URLString withObject:responseObject];
        if (contentModel) {
            success(task, contentModel);
        }else{
            failure(task,nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [QMUITips hideAllTipsInView:MYAPP.window];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        DLog(@"1111111111111111:%ld",    responses.statusCode);
        
        if (responses.statusCode == 401) {
            
            DLog(@"登录信息失效，请重新登录");
            [HttpHelper cancelAllRequest];
            [[UserInfoManager sharedManager] initEmptyData];
            [[UserInfoManager sharedManager] Login];
            return;
        }
        
        if ([error.domain isEqualToString:AFURLResponseSerializationErrorDomain]) {
            
            // server error
            id response = [NSJSONSerialization JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
            DLog(@"****%@",response);
            
            NSString *message = [NSString stringWithFormat:@"%@",response[@"message"]];
            NSString *status = [NSString stringWithFormat:@"%@",response[@"status"]];
            DLog(@"*****%@----%@",status,message);
            
            [ErrorHelpler showError:message];
            
            // response中包含服务端返回的内容
        } else if ([error.domain isEqualToString:NSCocoaErrorDomain]) {
            // server throw exception
            [ErrorHelpler showError:error.localizedDescription];
            
        } else if ([error.domain isEqualToString:NSURLErrorDomain]) {
            // network error
            [ErrorHelpler showError:error.localizedDescription];
        }
        failure(task, error);
        DLog(@"\n\nRESPONSE-URL:%@\nERROR:%@", URLString, error);
    }];
}
- (void)sendDelete:(NSString *)URLString
        parameters:(NSDictionary *)parameters
           success:(void (^)(NSURLSessionTask *operation, ResponseModel *responseObject))success
           failure:(void (^)(NSURLSessionTask *operation, NSError *error))failure{
    [QMUITips showLoadingInView:MYAPP.window];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:parameters];
    if (![dic[@"http_type"] isEqualToString:@"1"]) {
        [dic removeObjectForKey:@"http_type"];
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [self.manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    }else{
        self.manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json",@"text/javascript",@"application/html",@"application/x-www-form-urlencoded", nil];
        
        //申明返回的结果是json类型
        self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        //申明请求的数据是json类型
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    [self setCommonHeaderParameters];
    [self.manager DELETE:URLString parameters:[self addSign:dic] headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [QMUITips hideAllTipsInView:MYAPP.window];
        ResponseModel *contentModel = [self getResponseModel:URLString withObject:responseObject];
        if (contentModel) {
            success(task, contentModel);
        }else{
            failure(task,nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [QMUITips hideAllTipsInView:MYAPP.window];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        DLog(@"1111111111111111:%ld",    responses.statusCode);
        
        if (responses.statusCode == 401) {
            
            DLog(@"登录信息失效，请重新登录");
            [HttpHelper cancelAllRequest];
            [[UserInfoManager sharedManager] initEmptyData];
            [[UserInfoManager sharedManager] Login];
            return;
        }
        
        if ([error.domain isEqualToString:AFURLResponseSerializationErrorDomain]) {
            
            // server error
            id response = [NSJSONSerialization JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
            DLog(@"****%@",response);
            
            NSString *message = [NSString stringWithFormat:@"%@",response[@"message"]];
            NSString *status = [NSString stringWithFormat:@"%@",response[@"status"]];
            DLog(@"*****%@----%@",status,message);
            
            [ErrorHelpler showError:message];
            
            // response中包含服务端返回的内容
        } else if ([error.domain isEqualToString:NSCocoaErrorDomain]) {
            // server throw exception
            [ErrorHelpler showError:error.localizedDescription];
            
        } else if ([error.domain isEqualToString:NSURLErrorDomain]) {
            // network error
            [ErrorHelpler showError:error.localizedDescription];
        }
        failure(task, error);
        DLog(@"\n\nRESPONSE-URL:%@\nERROR:%@", URLString, error);
    }];
}

//发起请求
- (void)sendGet:(NSString *)URLString
     parameters:(NSDictionary *)parameters
        success:(void (^)(NSURLSessionTask *operation, ResponseModel *responseObject))success
        failure:(void (^)(NSURLSessionTask *operation, NSError *error))failure {
    [QMUITips showLoadingInView:MYAPP.window];
    DLog(@"paras===%@",parameters);
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:parameters];
    if (![[dic[@"http_type"] stringValue] isEqualToString:@"1"]) {
        [dic removeObjectForKey:@"http_type"];
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [self.manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        
    }else{
        self.manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json",@"image/jpeg", @"image/png", @"application/octet-stream", @"text/json",@"text/javascript",@"application/html",@"application/x-www-form-urlencoded", nil];
        
        //申明返回的结果是json类型
        self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        //申明请求的数据是json类型
        self.manager.requestSerializer=[AFJSONRequestSerializer serializer];
    }
    [self setCommonHeaderParameters];
    [self.manager GET:URLString parameters:[self addSign:dic] headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        [QMUITips hideAllTipsInView:MYAPP.window];
        //        [SVProgressHUD dismiss];
        ResponseModel *contentModel = [self getResponseModel:URLString withObject:responseObject];
        if (contentModel) {
            success(task, contentModel);
        }else{
            failure(task,nil);
        }
        
    } failure:^(NSURLSessionTask *task, NSError *error) {
        [QMUITips hideAllTipsInView:MYAPP.window];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        DLog(@"1111111111111111:%ld",    responses.statusCode);
        
        if (responses.statusCode == 401) {
            
            DLog(@"登录信息失效，请重新登录");
            [HttpHelper cancelAllRequest];
            [[UserInfoManager sharedManager] initEmptyData];
            [[UserInfoManager sharedManager] Login];
            return;
            
        }
        
        if ([error.domain isEqualToString:AFURLResponseSerializationErrorDomain]) {
            
            // server error
            id response = [NSJSONSerialization JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
            DLog(@"****%@",response);
            
            NSString *message = [NSString stringWithFormat:@"%@",response[@"message"]];
            DLog(@"----%@",message);
            
            [ErrorHelpler showError:message];
            // response中包含服务端返回的内容
            
        } else if ([error.domain isEqualToString:NSCocoaErrorDomain]) {
            // server throw exception
            [ErrorHelpler showError:error.localizedDescription];
            
        } else if ([error.domain isEqualToString:NSURLErrorDomain]) {
            // network error
            [ErrorHelpler showError:error.localizedDescription];
        }
        failure(task, error);
        DLog(@"\n\nRESPONSE-URL:%@\nERROR:%@", URLString, error);
        
    }];
}

-(void)uploadWithUrl:(NSString *)url withParas:(NSDictionary *)paras withImg:(NSDictionary *)imgDic success:(void (^)(NSURLSessionTask *operation, ResponseModel *responseObject))success
             failure:(void (^)(NSURLSessionTask *operation, NSError *error))failure{
    [QMUITips showLoadingInView:MYAPP.window];
    self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
    self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json",  @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    NSMutableDictionary * tempFileNames = [NSMutableDictionary new];
    for (int i = 0;i<imgDic.allKeys.count;i++) {
        [tempFileNames setObject:[NSString stringWithFormat:@"%@%d.png",[[TimeHelper share]getCurrentTimeStr],arc4random() % 10000] forKey:imgDic.allKeys[i]];
    }
    [tempFileNames addEntriesFromDictionary:paras];
    [self.manager POST:url parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传的参数(上传图片，以文件流的格式)
        NSArray *imgKeys = imgDic.allKeys;
        for (NSString *key in imgKeys) {
            NSData *tempData = UIImagePNGRepresentation(imgDic[key]);
            [formData appendPartWithFileData:tempData
                                        name:key
                                    fileName:tempFileNames[key]
                                    mimeType:@"image/png"];
        }
        NSArray *parasKeys = paras.allKeys;
        for (NSString *key in parasKeys) {
            [formData appendPartWithFormData:[paras[key] dataUsingEncoding:NSUTF8StringEncoding] name:key];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        DLog(@"uploadProgress==%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"上传成功");
        ResponseModel *contentModel = [self getResponseModel:url withObject:responseObject];
        if (contentModel) {
            success(task, contentModel);
        }else{
            failure(task,nil);
        }
        [QMUITips hideAllTipsInView:MYAPP.window];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [QMUITips hideAllTipsInView:MYAPP.window];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        DLog(@"1111111111111111:%ld",    responses.statusCode);
        
        if ([error.domain isEqualToString:AFURLResponseSerializationErrorDomain]) {
            
            // server error
            id response = [NSJSONSerialization JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
            DLog(@"****%@",response);
            
            NSString *message = [NSString stringWithFormat:@"%@",response[@"message"]];
            DLog(@"----%@",message);
            
            [ErrorHelpler showError:message];
            // response中包含服务端返回的内容
            
        } else if ([error.domain isEqualToString:NSCocoaErrorDomain]) {
            // server throw exception
            [ErrorHelpler showError:error.localizedDescription];
            
        } else if ([error.domain isEqualToString:NSURLErrorDomain]) {
            // network error
            [ErrorHelpler showError:error.localizedDescription];
        }
        failure(task, error);
        DLog(@"\n\nRESPONSE-URL:%@\nERROR:%@", url, error);
    }];
}

#pragma mark - 加密
//添加签名参数
- (NSDictionary *)addSign:(NSDictionary *)dictionary1{
    return dictionary1;
}

-(ResponseModel *)getResponseModel:(NSString *)url withObject:(id)responseObject{
    DLog(@"responseObject==%@",responseObject);
    ResponseModel *responseModel = [[ResponseModel alloc] initWithResponseObject:responseObject url:url];
    return responseModel;
}
-(NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


- (void)setCommonHeaderParameters {
    NSString *authorization = [NSString stringWithFormat:@"Bearer %@",@"ebb356c0-4870-11ee-a787-5bddcaf194da"];
    [self.manager.requestSerializer setValue:authorization forHTTPHeaderField:@"Authorization"];
    [self.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [self.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //    [self.manager.requestSerializer setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forHTTPHeaderField:@"appVersion"];
    //    [self.manager.requestSerializer setValue:[UIDevice currentDevice].systemVersion forHTTPHeaderField:@"systemVersion"];
    //    [self.manager.requestSerializer setValue:[UIDevice currentDevice].systemName forHTTPHeaderField:@"systemName"];
    //    [self.manager.requestSerializer setValue:[UIDevice currentDevice].localizedModel forHTTPHeaderField:@"systemModel"];
}

#pragma mark - cancel
+ (void)cancelAllRequest {
    [[HttpHelper sharedInstance].manager.operationQueue.operations enumerateObjectsUsingBlock:^(__kindof NSOperation * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSOperation *oper = (NSOperation *)obj;
        
        [oper cancel];
    }];
    [[HttpHelper sharedInstance].manager.tasks enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSURLSessionTask *oper = (NSURLSessionTask *)obj;
        
        [oper cancel];
    }];
}

+ (void)cancelRequestWithPath:(NSString *)path {
    [[HttpHelper sharedInstance].manager.tasks enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *url = [obj.currentRequest.URL absoluteString];
        NSRange range = [url rangeOfString:path];
        if (range.location != NSNotFound) {
            DLog(@"cancelled request : %@", path);
            [obj cancel];
        }
    }];
}

@end
